package djboom.materials.display.devices {
	import djboom.materials.Work;
	import djboom.materials.core.BitmapDataCore;
	import djboom.materials.display.elements.HotSpot;
	import djboom.materials.display.page.work2.Page4;
	import djboom.materials.events.BeamScalesEvent;
	import djboom.materials.events.InstructionEvent;
	import djboom.utils.WeakReference;

	import com.greensock.TimelineMax;
	import com.greensock.TweenAlign;
	import com.greensock.TweenLite;
	import com.greensock.TweenMax;
	import com.greensock.easing.Cubic;
	import com.greensock.easing.Linear;
	import com.greensock.easing.Quad;

	import org.casalib.collection.UniqueList;
	import org.casalib.display.CasaBitmap;
	import org.casalib.display.CasaShape;
	import org.casalib.display.CasaSprite;
	import org.casalib.util.ConversionUtil;
	import org.casalib.util.StageReference;

	import flash.display.PixelSnapping;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	/**
	 * Коромысловые весы.
	 * <br>
	 * 
	 * @author DJ BooM 
	 * @since 21.09.2010
	 * 
	 */

	public class BeamScales extends CasaSprite {

		// ----------------------------------------------------------------------------
		// Константы класса.
		// ----------------------------------------------------------------------------

		private static const SUPPORT:String = "beamscales.Support";		private static const SWITCH:String = "beamscales.Switch";		private static const SCALE_LEFT:String = "beamscales.ScaleLeft";		private static const SCALE_RIGHT:String = "beamscales.ScaleRight";		private static const BEAM:String = "beamscales.Beam";		private static const BOB:String = "beamscales.Bob";		private static const ARROW:String = "beamscales.Arrow";		
	
		// ----------------------------------------------------------------------------
		// Свойства класса.
		// ----------------------------------------------------------------------------
	
		private var ROTATE_POINT_ARROW:Point = new Point(9, 40);		private var ROTATE_POINT_BEAM:Point = new Point(186, 14);

		private var _scalesTimeline:TimelineMax;

		private var _materialWeakRef:WeakReference;
		private var _material:CasaSprite;

		private var _supportBitmap:CasaBitmap;
		private var _scaleLeftBitmap:CasaBitmap;
		private var _scaleRightBitmap:CasaBitmap;
		private var _beamBitmap:CasaBitmap;
		private var _bobBitmap:CasaBitmap;
		private var _arrowBitmap:CasaBitmap;

		private var _weightSmall:Weight;
		private var _weightMiddle:Weight;
		private var _weightBig:Weight;
		private var _currentWeight:Weight;

		private var _weightAray:Array;

		private var _weightHitArea:CasaShape;

		private var _weightsList:UniqueList = new UniqueList();

		private var _totalWeights:Number;
		private var _rightWeights:Number;

		private var _switchHS:HotSpot;

		private var _sampleMaterialPhase:String;

		// ----------------------------------------------------------------------------
		// Конструктор.
		// ----------------------------------------------------------------------------

		public function BeamScales() {
			super();
			
			_supportBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(SUPPORT));
			_supportBitmap.x = 4;			_supportBitmap.y = 58;
			addChild(_supportBitmap);
			
			_switchHS = new HotSpot();
			_switchHS.drawBitmap(BitmapDataCore.getBitmapData(SWITCH));
			_switchHS.x = 223;
			_switchHS.y = 381;
			addChild(_switchHS);
			
			_scaleLeftBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(SCALE_LEFT), PixelSnapping.AUTO, true);
			_scaleLeftBitmap.y = 51 + 15;
			addChild(_scaleLeftBitmap);
            
			_scaleRightBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(SCALE_RIGHT), PixelSnapping.AUTO, true);
			_scaleRightBitmap.x = 328;			_scaleRightBitmap.y = 51 + 15;
			addChild(_scaleRightBitmap);
            
			_beamBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(BEAM), PixelSnapping.AUTO, true);
			_beamBitmap.x = 52;
			_beamBitmap.y = 26 + 15;
			addChild(_beamBitmap);
            
			_bobBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(BOB));
			_bobBitmap.x = 148;
			_bobBitmap.y = 52;
			addChild(_bobBitmap);
            
			_arrowBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(ARROW), PixelSnapping.AUTO, true);
			_arrowBitmap.x = 229;
			_arrowBitmap.y = 15;
			addChild(_arrowBitmap);
			
			addEventListener(Event.ADDED_TO_STAGE, initSprite);
		}	 

		// ----------------------------------------------------------------------------
		// Приватные методы класса.
		// ----------------------------------------------------------------------------
			
		// ----------------------------------------------------------------------------
		// Видимые методы класса.
		// ----------------------------------------------------------------------------
		
		// ----------------------------------------------------------------------------
		// Переопределенные методы.
		// ----------------------------------------------------------------------------
		
		// ----------------------------------------------------------------------------
		// Обработчики событий.
		// ----------------------------------------------------------------------------

		private function initSprite(event:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, initSprite);
            
			addEventListener(Event.REMOVED_FROM_STAGE, clearContent);
		}

		private function clearContent(event:Event):void {
			removeEventListener(Event.REMOVED_FROM_STAGE, clearContent);
			
			_material = null;
            
			_materialWeakRef.dispose();
			_materialWeakRef = null;
		}

		// ----------------------------------------------------------------------------
		// Публичные методы.
		// ----------------------------------------------------------------------------

		/**
		 * Приводим весы рабочее положение.
		 * Поворачиваем ручку и стрелка отклоняется незначительно влево – вправо
		 * при этом коромысло с чашками качается вверх – вниз,
		 * затем стрелка останавливается на отметке «0».
		 * 
		 */

		public function enable(sampleMaterialPhase:String):void {
			_sampleMaterialPhase = sampleMaterialPhase;
			
			_switchHS.addEventListener(MouseEvent.CLICK, nullScale);
		}

		private function nullScale(event:MouseEvent):void {
			_switchHS.removeEventListener(MouseEvent.CLICK, nullScale);
			
			TweenLite.to(_switchHS, 0.1, {transformAroundCenter:{rotation: 90}});
			
			_scalesTimeline = new TimelineMax();
			
			if (_sampleMaterialPhase == Page4.MATERIAL_PHASE_GLASS) {
				_scalesTimeline.insertMultiple(TweenMax.allTo([_material, _scaleLeftBitmap, _scaleRightBitmap, _beamBitmap, _arrowBitmap], 0.5, {y: "-15"}, 0, scalesNull));
			} else {
				_scalesTimeline.insertMultiple(TweenMax.allTo([_scaleLeftBitmap, _scaleRightBitmap, _beamBitmap, _arrowBitmap], 0.5, {y: "-15"}, 0, scalesNull));	
			}
		}

		private function scalesNull():void {
			_scalesTimeline.clear();
			_scalesTimeline.kill();
			
			var tweensTime:Number = 0.3;
			var rotationAngle:Number = 2;
			
			var tweensLeft:Array = [];
			var tweensRight:Array = [];
			var tweensNull:Array = [];
			
			if (_sampleMaterialPhase == Page4.MATERIAL_PHASE_GLASS) {
				tweensLeft.push(TweenLite.to(_arrowBitmap, tweensTime, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: rotationAngle}, ease: Linear.easeNone}));
				tweensLeft.push(TweenLite.to(_beamBitmap, tweensTime, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: rotationAngle}, ease: Linear.easeNone}));
				tweensLeft.push(TweenLite.to(_scaleLeftBitmap, tweensTime, {y: 51 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));				tweensLeft.push(TweenLite.to(_material, tweensTime, {y: 546 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
				tweensLeft.push(TweenLite.to(_scaleRightBitmap, tweensTime, {y: 51 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
            
				tweensRight.push(TweenLite.to(_arrowBitmap, tweensTime * 2, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: -rotationAngle}, ease: Linear.easeNone}));
				tweensRight.push(TweenLite.to(_beamBitmap, tweensTime * 2, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: -rotationAngle}, ease: Linear.easeNone}));
				tweensRight.push(TweenLite.to(_scaleLeftBitmap, tweensTime * 2, {y: 51 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));				tweensRight.push(TweenLite.to(_material, tweensTime * 2, {y: 546 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
				tweensRight.push(TweenLite.to(_scaleRightBitmap, tweensTime * 2, {y: 51 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
            
				tweensNull.push(TweenLite.to(_arrowBitmap, tweensTime, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: 0}, ease: Linear.easeNone}));
				tweensNull.push(TweenLite.to(_beamBitmap, tweensTime, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: 0}, ease: Linear.easeNone}));
				tweensNull.push(TweenLite.to(_scaleLeftBitmap, tweensTime, {y: 51, ease: Linear.easeNone}));				tweensNull.push(TweenLite.to(_material, tweensTime, {y: 546, ease: Linear.easeNone}));
				tweensNull.push(TweenLite.to(_scaleRightBitmap, tweensTime, {y: 51, ease: Linear.easeNone}));  
			} else {
				tweensLeft.push(TweenLite.to(_arrowBitmap, tweensTime, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: rotationAngle}, ease: Linear.easeNone}));
				tweensLeft.push(TweenLite.to(_beamBitmap, tweensTime, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: rotationAngle}, ease: Linear.easeNone}));
				tweensLeft.push(TweenLite.to(_scaleLeftBitmap, tweensTime, {y: 51 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
				tweensLeft.push(TweenLite.to(_scaleRightBitmap, tweensTime, {y: 51 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
            
				tweensRight.push(TweenLite.to(_arrowBitmap, tweensTime * 2, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: -rotationAngle}, ease: Linear.easeNone}));
				tweensRight.push(TweenLite.to(_beamBitmap, tweensTime * 2, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: -rotationAngle}, ease: Linear.easeNone}));
				tweensRight.push(TweenLite.to(_scaleLeftBitmap, tweensTime * 2, {y: 51 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
				tweensRight.push(TweenLite.to(_scaleRightBitmap, tweensTime * 2, {y: 51 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
            
				tweensNull.push(TweenLite.to(_arrowBitmap, tweensTime, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: 0}, ease: Linear.easeNone}));
				tweensNull.push(TweenLite.to(_beamBitmap, tweensTime, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: 0}, ease: Linear.easeNone}));
				tweensNull.push(TweenLite.to(_scaleLeftBitmap, tweensTime, {y: 51, ease: Linear.easeNone}));
				tweensNull.push(TweenLite.to(_scaleRightBitmap, tweensTime, {y: 51, ease: Linear.easeNone}));	
			}
			
			_scalesTimeline = new TimelineMax({onComplete: scalesReady, align: TweenAlign.NORMAL});
			_scalesTimeline.insertMultiple(tweensLeft, 0);
			_scalesTimeline.insertMultiple(tweensRight, tweensTime);
			_scalesTimeline.insertMultiple(tweensNull, tweensTime * 3);
		}

		private function scalesReady():void {
			_scalesTimeline.clear();
			_scalesTimeline.kill();
            
			dispatchEvent(new InstructionEvent(InstructionEvent.REFRESH));
			
			var beamScalesEvent:BeamScalesEvent = new BeamScalesEvent(BeamScalesEvent.ENABLE_SAMPLE);
			beamScalesEvent.sampleMaterialPhase = _sampleMaterialPhase;
			dispatchEvent(beamScalesEvent);
		}

		
		
		/**
		 * Выводим весы из рабочего положения.
		 * 
		 */

		public function disable():void {
			_switchHS.addEventListener(MouseEvent.CLICK, disableScale);
		}

		private function disableScale(event:MouseEvent):void {
			_switchHS.removeEventListener(MouseEvent.CLICK, disableScale);
            
			TweenLite.to(_switchHS, 0.1, {transformAroundCenter:{rotation: 0}});
			
			var tweenArray:Array = [_material, _scaleLeftBitmap, _scaleRightBitmap, _beamBitmap, _arrowBitmap];
			
			for (var i:int = 0;i < _weightsList.size;i++) {
				var weight:Weight = _weightsList.getItemAt(i) as Weight;
				tweenArray.push(weight);
			}
            
			_scalesTimeline = new TimelineMax();
			_scalesTimeline.insertMultiple(TweenMax.allTo(tweenArray, 0.5, {y: "15"}, 0));
             
			dispatchEvent(new InstructionEvent(InstructionEvent.REFRESH));
		}

		/**
		 * На левую чашку весов помещается образец.
		 * Коромысло опускается влево, стрелка отклоняется вправо, левая чашка идет вниз,
		 * правая – вверх (вместе со стрелкой всегда движутся коромысло и чашки).
		 * На правую чашку помещаются гири, чтобы привести весы в равновесие.
		 * Весы придут в равновесие, если поставим большую и среднюю гири.
		 * Если поставим только одну гирю, то стрелка отклонится влево, но не дойдет до нуля.
		 * Если поставим большую и маленькую гири, то стрелка ещё отклонится влево, но не дойдет до нуля.
		 * Если поставим большую, маленькую и среднюю гири, то стрелка уйдет за ноль,
		 * а правая чашка опустится ниже левой.
		 * Если уберем маленькую гирю и оставим большую и среднюю, то весы придут в равновесие.
		 * Когда весы приходят в равновесие, появляется табло со значением массы.
		 * 
		 */

		public function balanceMaterial(materialReference:CasaSprite, rightWeights:Number):void {
			_rightWeights = rightWeights;
			
			_materialWeakRef = new WeakReference(materialReference);
            
			_material = _materialWeakRef.value as CasaSprite;
            
			var tweensTime:Number = 0.3;
			var rotationAngle:Number = 5;
            
			var tweens:Array = [];
			
			var heightWay:Number = 164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle));
			
            
			tweens.push(TweenLite.to(_arrowBitmap, tweensTime, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: -rotationAngle}, ease: Linear.easeNone}));
			tweens.push(TweenLite.to(_beamBitmap, tweensTime, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: -rotationAngle}, ease: Linear.easeNone}));
			tweens.push(TweenLite.to(_scaleLeftBitmap, tweensTime, {y: 51 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
			tweens.push(TweenLite.to(_scaleRightBitmap, tweensTime, {y: 51 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));			tweens.push(TweenLite.to(_material, tweensTime, {y: String(int(heightWay)), ease: Linear.easeNone}));
            
			_scalesTimeline = new TimelineMax({onComplete: showWeights, align: TweenAlign.NORMAL});
			_scalesTimeline.insertMultiple(tweens);            
		}

		/**
		 * Показываем и включаем гирьки.
		 * 
		 */

		private function showWeights():void {
			if (_weightAray == null) {
				_weightAray = [];
             
				_weightSmall = new Weight(Weight.WEIGHT_SMALL, BitmapDataCore.WORK2_WEIGHT1);
				_weightSmall.x = -126;
				_weightSmall.y = _supportBitmap.y + _supportBitmap.height - _weightSmall.height - 60;
				addChild(_weightSmall);
             
				_weightAray.push(_weightSmall);
             
				_weightMiddle = new Weight(Weight.WEIGHT_MIDDLE, BitmapDataCore.WORK2_WEIGHT2);
				_weightMiddle.x = -95;
				_weightMiddle.y = _supportBitmap.y + _supportBitmap.height - _weightMiddle.height - 60;
				addChild(_weightMiddle);
             
				_weightAray.push(_weightMiddle);
             
				_weightBig = new Weight(Weight.WEIGHT_BIG, BitmapDataCore.WORK2_WEIGHT3);
				_weightBig.x = -54;
				_weightBig.y = _supportBitmap.y + _supportBitmap.height - _weightBig.height - 60;
				addChild(_weightBig);
             
				_weightAray.push(_weightBig);
             
				TweenMax.allTo(_weightAray, 0, {autoAlpha: 0});
				TweenMax.allTo(_weightAray, 0.3, {autoAlpha: 1, y: "60", ease: Quad.easeIn}, 0.1);
				
				_weightHitArea = new CasaShape();
				_weightHitArea.graphics.beginFill(0, 0);				_weightHitArea.graphics.drawRect(0, 0, 110, 190);				_weightHitArea.graphics.endFill();
				_weightHitArea.x = 350;				_weightHitArea.y = 140;
				
				addChild(_weightHitArea);
				
				// включаем таскание гирек
				_weightSmall.addEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);				_weightMiddle.addEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);				_weightBig.addEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
			} else {
				_weightAray = [];
				
				_weightAray.push(_weightSmall);
				_weightAray.push(_weightMiddle);
				_weightAray.push(_weightBig);
             
				_weightHitArea.visible = true;
				addChild(_weightHitArea);
                
				// включаем таскание гирек
				_weightSmall.addEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
				_weightMiddle.addEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
				_weightBig.addEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
			}
		}

		private function setupDragWeight(event:MouseEvent):void {
			_currentWeight = event.currentTarget as Weight;
			addChild(_currentWeight);

			_currentWeight.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
             
			_currentWeight.startDrag(false, new Rectangle(-527, -172, Work.WIDTH - 6 - _currentWeight.width, Work.HEIGHT - 178 - _currentWeight.height));
            
			_currentWeight.addEventListener(MouseEvent.MOUSE_UP, stopDragSprite);
            
			StageReference.getStage().addEventListener(MouseEvent.MOUSE_UP, stopDragSprite);
		}

		
		/**
		 * Останавливаем таскание объекта.
		 * 
		 */

		private function stopDragSprite(event:MouseEvent = null):void {
			_currentWeight.stopDrag();
            
			StageReference.getStage().removeEventListener(MouseEvent.MOUSE_UP, stopDragSprite);
			_currentWeight.removeEventListener(MouseEvent.MOUSE_UP, stopDragSprite);
            
			var time:Number = 0.2;
            
			if (_currentWeight.hitTestObject(_weightHitArea)) {
				_weightsList.addItem(_currentWeight);
			} else {
				_weightsList.removeItem(_currentWeight);           
			}
			
			_currentWeight.addEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
			
			/**
			 * Считаем общий вес.
			 * 
			 */

			_totalWeights = 0;

			for (var i:int = 0;i < _weightsList.size;i++) {
				var weight:Weight = _weightsList.getItemAt(i) as Weight;
				
				_totalWeights += weight.weight; 
			}
			
			if (_currentWeight.hitTestObject(_weightHitArea)) {
				TweenLite.to(_currentWeight, time, {y:  _supportBitmap.y + _supportBitmap.height - _currentWeight.height - 65, ease: Quad.easeIn, onComplete: animateScales});
			} else {
				TweenLite.to(_currentWeight, time, {y:  _supportBitmap.y + _supportBitmap.height - _currentWeight.height, ease: Quad.easeIn, onComplete: animateScales});
			}

			
			if (_totalWeights == _rightWeights) {
				_weightHitArea.visible = false;
				removeChild(_weightHitArea);
                
				_weightSmall.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
				_weightMiddle.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
				_weightBig.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
                
				dispatchEvent(new InstructionEvent(InstructionEvent.REFRESH));
			}
		}

		private function animateScales():void {
			var tweensTime:Number = 0.3;
			var rotationAngle:Number = (5 / _rightWeights) * _totalWeights - 5;;
			var tweens:Array = [];
			
			tweens.push(TweenLite.to(_arrowBitmap, tweensTime, {transformAroundPoint: {point: new Point(_arrowBitmap.x + ROTATE_POINT_ARROW.x, _arrowBitmap.y + ROTATE_POINT_ARROW.y), rotation: rotationAngle}, ease: Linear.easeNone}));
			tweens.push(TweenLite.to(_beamBitmap, tweensTime, {transformAroundPoint: {point: new Point(_beamBitmap.x + ROTATE_POINT_BEAM.x, _beamBitmap.y + ROTATE_POINT_BEAM.y), rotation: rotationAngle}, ease: Linear.easeNone}));
            
			tweens.push(TweenLite.to(_scaleLeftBitmap, tweensTime, {y: 51 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
			tweens.push(TweenLite.to(_scaleRightBitmap, tweensTime, {y: 51 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));
			
			if (_sampleMaterialPhase == Page4.MATERIAL_PHASE_GLASS) {
				tweens.push(TweenLite.to(_material, tweensTime, {y: 546 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))), ease: Linear.easeNone}));	
			} else {
				tweens.push(TweenLite.to(_material, tweensTime, {y: 51 - (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle))) + _material.height + 495, ease: Linear.easeNone}));	
			}
                
			for (var i:int = 0;i < _weightsList.size;i++) {
				var weight:Weight = _weightsList.getItemAt(i) as Weight;
				tweens.push(TweenLite.to(weight, tweensTime, {y: -109 + _supportBitmap.y + _supportBitmap.height - weight.height + (51 + (164 * Math.tan(ConversionUtil.degreesToRadians(rotationAngle)))), ease: Linear.easeNone}));
			}
            
			_scalesTimeline = new TimelineMax({align: TweenAlign.NORMAL});
			_scalesTimeline.insertMultiple(tweens); 
		}

		
		public function removeWeights():void {
			_weightSmall.addEventListener(MouseEvent.MOUSE_DOWN, dragWeightOfScale);
                
			_weightMiddle.addEventListener(MouseEvent.MOUSE_DOWN, dragWeightOfScale);
                
			_weightBig.addEventListener(MouseEvent.MOUSE_DOWN, dragWeightOfScale);
		}

		private function dragWeightOfScale(event:MouseEvent):void {
			_currentWeight = event.currentTarget as Weight;
			addChild(_currentWeight);

			_currentWeight.removeEventListener(MouseEvent.MOUSE_DOWN, dragWeightOfScale);
             
			_currentWeight.startDrag(false, new Rectangle(-527, -172, Work.WIDTH - 6 - _currentWeight.width, Work.HEIGHT - 178 - _currentWeight.height));
            
			_currentWeight.addEventListener(MouseEvent.MOUSE_UP, stopDragOfScale);
            
			StageReference.getStage().addEventListener(MouseEvent.MOUSE_UP, stopDragOfScale);
		}

		private function stopDragOfScale(event:MouseEvent):void {
			_currentWeight.stopDrag();
            
			StageReference.getStage().removeEventListener(MouseEvent.MOUSE_UP, stopDragOfScale);
			_currentWeight.removeEventListener(MouseEvent.MOUSE_UP, stopDragOfScale);
            
			var time:Number = 0.3;
            
			TweenLite.to(_currentWeight, time, {y:  _supportBitmap.y + _supportBitmap.height - _currentWeight.height, ease: Quad.easeIn});
                
			_weightsList.removeItem(_currentWeight);
			
			if (_weightsList.size == 0) {
				dispatchEvent(new BeamScalesEvent(BeamScalesEvent.REMOVE_WEIGHTS));
				
				_weightSmall.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
				_weightMiddle.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
				_weightBig.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragWeight);
			}
		}

		/**
		 * Сдвигаем гирьки вправо.
		 * 
		 */

		public function tweenWeights():void {
			TweenLite.to(_weightSmall, 0.5, {x: -126, ease: Cubic.easeInOut});			TweenLite.to(_weightMiddle, 0.5, {x: -95, ease: Cubic.easeInOut});			TweenLite.to(_weightBig, 0.5, {x: -54, ease: Cubic.easeInOut});
		}

		public function remove():void {
			_switchHS.addEventListener(MouseEvent.CLICK, removeScale);
		}

		private function removeScale(event:MouseEvent):void {
			_switchHS.removeEventListener(MouseEvent.CLICK, removeScale);
			
			TweenLite.to(_switchHS, 0.1, {transformAroundCenter:{rotation: 0}});
			
			dispatchEvent(new BeamScalesEvent(BeamScalesEvent.DESTROY));
		}

		// ----------------------------------------------------------------------------
		// Методы доступа.
		// ----------------------------------------------------------------------------

		public function get weightsList():UniqueList {
			return _weightsList;
		}
	}
}
